import { Component, OnInit, Input } from '@angular/core';
import {EventSource, EventService} from '../services/event.service';
import { Calendar, Params } from '../entity/Calendar';
import { CalendarService } from '../services/calendar.service';
import {Utils} from '../common/Common';
import {BookedResult} from '../entity/TT';

@Component({
  selector: 'app-calendar',
  templateUrl: './calendar.component.html',
  styleUrls: ['./calendar.component.scss']
})
export class CalendarComponent implements OnInit {

  @Input()
  eventSource: EventSource;
  @Input()
  result: BookedResult;

  calendar: Calendar;

  params: Params;

  activedDay: any;

  constructor(
    private eventService: EventService,
    private calendarServer: CalendarService,
  )
  {

  }

  ngOnInit() {
    this.params = {seek: 0, result: this.result};
    this.loadCalendar();
  }

  loadCalendar(): void {

    this.calendarServer.getCalendar(this.params)
    .subscribe( calendar => {
      this.calendar = calendar;
      const  today = this.getToday();
      if (today) {
        this.onSelectDay(today);
      }
    });
  }

  onSelectDay(day: any) {
    this.activedDay = day;
    this.eventService.sendEvent(this.eventSource, day);
  }

  previous(): void {
    if(this.params.seek === -5)
      return;

    this.params.seek -= 1;
    this.loadCalendar();
  }

  next(): void {
    if(this.params.seek === 3)
      return;

    this.params.seek += 1;
    this.loadCalendar();
  }

  getToday(): any {

    for (let i = 0; i < this.calendar.dateList.length; i++) {
      const d = this.calendar.dateList[i];
      const ts = Utils.nowTime();
      if (d.localDate <= ts && ts < this.calendar.dateList[i + 1].localDate) {
        return d;
      }
    }


  }
}
